package servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.codec.binary.Base64;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import service.UploadService;
import vo.Upload;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UploadService service=new UploadService();
	private static String pathStr = "d:/upload";

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String method = request.getParameter("method");
		if("upload".equals(method)){
			upload(request,response);
		}else if("delete".equals(method)){
			delete(request,response);
		}else if("down".equals(method)){
			download(request,response);
		}else if("upload1".equals(method)){
			upload1(request,response);
		}
	}

	private synchronized void upload1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SmartUpload su=new SmartUpload();
		su.initialize(getServletConfig(), request, response);
		su.setMaxFileSize(1024*1024*10);
		su.setTotalMaxFileSize(1024*1024*40);
		
		//su.setAllowedFilesList("txt,jpg,gif,png");
		//su.setDeniedFilesList("rar,jsp,js");
		try {
				su.upload();
				Request req= su.getRequest();
				String notes = req.getParameter("notes");
				String filename=su.getFiles().getFile(0).getFileName();
				String uuid=UUID.randomUUID().toString();
				Upload upload=new Upload();
				upload.setFilename(filename);
				upload.setNotes(notes);
				upload.setUuid(uuid);
				service.save(upload);
				com.jspsmart.upload.File file = su.getFiles().getFile(0);
				file.saveAs(pathStr+"/"+uuid+".tmp",SmartUpload.SAVE_AUTO );
			} catch (SmartUploadException e) {
				e.printStackTrace();
			}
		response.sendRedirect("index");
	}

	private void download(HttpServletRequest request, HttpServletResponse response) {
		String idstr = request.getParameter("id");
		Integer id=Integer.parseInt(idstr);
		String saveName=service.getFileSaveName(id);
		String filename=service.getFilename(id);
		filename=getStr(request, filename);
		File file=new File(pathStr, saveName);
		if(file.exists()){
			FileInputStream fis;
			try {
				fis = new FileInputStream(file);
				response.setContentType("application/x-msdownload");
				response.addHeader("Content-Disposition", "attachment; filename=" + filename );
				ServletOutputStream out = response.getOutputStream();
				byte[] buf=new byte[2048];
				int n=0;
				while((n=fis.read(buf))!=-1){
					out.write(buf, 0, n);
				}
				fis.close();
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private synchronized void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String idstr = request.getParameter("id");
		Integer id=Integer.parseInt(idstr);
		String filename=service.getFileSaveName(id);
		File file=new File(pathStr,filename);
		if(file.exists()){
			file.delete();
		}
		service.delete(id);
		response.sendRedirect("index.html");
	}

	private synchronized void upload(HttpServletRequest request, HttpServletResponse response) {
		File path=new File(pathStr);
		if(!path.exists()||!path.isDirectory()){
			path.mkdir();
		}
		DiskFileItemFactory factory=new DiskFileItemFactory();
		
		factory.setSizeThreshold(1024*1024*3);
	
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

		FileUpload fileUpload=new FileUpload(factory);

		fileUpload.setFileSizeMax(1024*1024*5);

		fileUpload.setSizeMax(1024*1024*12);

		fileUpload.setHeaderEncoding("utf-8");
		List<FileItem> items;
		String notes=null;
		String filename=null;
		FileItem saveItem = null;
		try {
			items = fileUpload.parseRequest(new ServletRequestContext(request));
			for (FileItem item : items) {
				if(item.isFormField()){
					if("notes".equals(item.getFieldName())){
						notes=item.getString("utf-8");
					}
				}else{
					if("myfile".equals(item.getFieldName())){
						filename=new File(item.getName()).getName();
						saveItem=item;
					}
				}
			}
			Upload upload=new Upload();
			upload.setFilename(filename);
			upload.setNotes(notes);
			String uuid=UUID.randomUUID().toString();
			upload.setUuid(uuid);
			service.save(upload);
			File saveFile=new File(path, uuid+".tmp");
			saveItem.write(saveFile);
			//filename = getServletContext().getContextPath()+"/upload/"+filename;
			//request.getRequestDispatcher("j1.jsp").forward(request, response);
			response.sendRedirect("index.html");
			
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private String getStr(HttpServletRequest request, String fileName) {
		String downloadFileName = null;
		
        String agent = request.getHeader("USER-AGENT");  
         try {
            	 if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
            		 downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
            	 }else{
            		 downloadFileName =  java.net.URLEncoder.encode(fileName, "UTF-8");
            	 }
		} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
		}
        return downloadFileName;
	}


}
